package com.adong.tv.ui;

import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;
import androidx.leanback.app.BrowseSupportFragment;

import com.adong.tv.R;
import com.adong.tv.ui.fragment.MainFragment;

/**
 * 主Activity
 */
public class MainActivity extends FragmentActivity {
    
    private static final int BACK_PRESS_INTERVAL = 2000;
    private long backPressTime = 0;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        if (savedInstanceState == null) {
            // 初始化主浏览页面
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.main_container, new MainFragment())
                    .commitNow();
        }
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 处理返回键，连续按两次退出
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            BrowseSupportFragment browseSupportFragment = 
                    (BrowseSupportFragment) getSupportFragmentManager().findFragmentById(R.id.main_container);
            
            // 如果是主浏览页面，则处理双击退出
            if (browseSupportFragment != null && browseSupportFragment instanceof MainFragment) {
                if (System.currentTimeMillis() - backPressTime > BACK_PRESS_INTERVAL) {
                    backPressTime = System.currentTimeMillis();
                    Toast.makeText(this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
                    return true;
                } else {
                    finish();
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }
} 